/**
 * Created by lwy on 2017/9/5.
 */
var lnt;
var shopPhone;
var shopAddress;
var shopName;
var shopId = GetQueryString('shopId');
var userId = GetQueryString('userId');
var goodsPage = 1;
$(function () {
    if(userId==undefined||userId==null||userId==""){
        userId = "";
    }else{
        setItem('userId',userId);
    }
})

function doAjax(){
    $.ajax({
        url:'/shopC/shopDetailed_V2.json',
        dataType:'json',
        data:{
            shopId:shopId,
        },
        type:'post',
        async: false,
        success:function(data){
            initShop(data.datas);
            if(data.datas.customersdatas.length>0){
                initComment(data.datas);
            }else{
                $('.comment-big-box').hide();
            }
        }
    })
}

doAjax();

//店铺信息
function initShop(a){
    lnt = a.address;
    shopPhone = a.phone;
    shopName = a.shopName;
    shopAddress = a.shopAddress;
    $('#MainImg').attr('src', a.mainImg);
    $('.title').html(shopName);
    $('#shopPhone').attr('href', 'tel:'+shopPhone+'');
    $('.detail_box').append(a.detailImg);
    $('.detail-box img').on('load',function () {
        $('.detail-box img').css('width','100%');
    })

    showStar(a.shopGraded);
    $('#address').html(shopAddress);
    if(a.goodsDatas.length>0){
        initGoods(a.goodsDatas);
    }else{
        $('.goods-box').hide();
    }
}

//商品
function initGoods(b){
    var otherGoods = '';
        if(b.length>2){
            otherGoods = '<div class="other-goods">更多<img src="../img/other_icon.png"/></div>';
        }else{
            otherGoods = '';
        }
        var bLength =1;
    if(b.length==1){
        bLength = 1;
    }else{
        bLength = 2;
    }
    for(var i=0;i<bLength;i++){
        $('<div class="goods mui-clearfix" id="'+b[i].id+'"><div class="goods-img">'+
            '<img src="'+b[i].mainImage+'" alt="商品">'+
            '</div><div class="goods-title-box">'+
            '<div class="goods-title">'+b[i].name+'</div>'+
            '<div class="goods-price">¥'+b[i].memberPrice+'</div>'+
            '<div class="invalid-price">¥'+b[i].marketPrice+'</div></div>'+
            '<div class="view-detail">查看详情<img src="../img/order-more.png"></div>'+
            '</div>').appendTo($('.goods-box'));
    }
    $(otherGoods).appendTo($('.goods-box'));


        //点击更多
    $('.other-goods').click(function () {
        for(var j=2;j< b.length;j++){
            $('<div class="goods mui-clearfix" id="'+b[j].id+'"><div class="goods-img">'+
                '<img src="'+b[j].mainImage+'" alt="商品">'+
                '</div><div class="goods-title-box">'+
                '<div class="goods-title">'+b[j].name+'</div>'+
                '<div class="goods-price">¥'+b[j].memberPrice+'</div>'+
                '<div class="invalid-price">¥'+b[j].marketPrice+'</div></div>'+
                '<div class="view-detail">查看详情<img src="../img/order-more.png"></div>'+
                '</div>').insertAfter($('.goods-h3'));
        }
        $('.other-goods').hide();
        if(b.length<20){
            $('.other-goods').hide();
        }else{
            $('<div class="other-goods2">更多<img src="../img/other_icon.png"/></div>').appendTo($('.goods-box'));
        }
        $('.other-goods2').click(function () {
            goodsPage++;
            $.ajax({
                url:'/goodsC/showGoods.json',
                dataType:'json',
                data:{
                    shopId:shopId,
                    page:goodsPage,
                },
                type:'post',
                success:function (data) {
                    if(data.datas.length==0){
                        $('.other-goods2').html('没有更多数据了')
                        $('.other-goods2').css('pointer-events','none')
                    }else{
                        $('.other-goods2').hide();
                        for(var k=0;k< data.datas.length;j++){
                            $('<div class="goods mui-clearfix" id="'+data.datas[k].id+'"><div class="goods-img">'+
                                '<img src="'+data.datas[k].mainImage+'" alt="商品">'+
                                '</div><div class="goods-title-box">'+
                                '<div class="goods-title">'+data.datas[k].name+'</div>'+
                                '<div class="goods-price">¥'+data.datas[k].memberPrice+'</div>'+
                                '<div class="invalid-price">¥'+data.datas[k].marketPrice+'</div></div>'+
                                '<div class="view-detail">查看详情<img src="../img/order-more.png"></div>'+
                                '</div>').appendTo($('.goods-box'));
                        }
                        $('<div class="other-goods2">更多<img src="../img/other_icon.png"/></div>').appendTo($('.goods-box'));
                    }
                }
            })
        })
    })
}

//进商品详情
$('body').on('click','.goods',function () {
    var goodsId = $(this).attr('id');
    window.location.href="goods_v2.html?goodsId="+goodsId+'&shopId='+shopId;
})

//评价
function initComment(c){
    showStar3(c.shopGraded);
    $('#shopScore').html(c.shopGraded);
    $('.comment-number i').html('('+c.userCustomersSum+')')
    for(var k=0;k< c.commentsSumdatas.length;k++){
        var borderStyle = '';
        if(c.commentsSumdatas[k].commentsType=="差评"){
            borderStyle = 'border:1px solid #c5c5c5;color:#c5c5c5'
        }else{
            borderStyle = '';
        }
        $('<div value="'+ c.commentsSumdatas[k].commentsTypeValue+'" style="'+borderStyle+'">'+ c.commentsSumdatas[k].commentsType+'('+c.commentsSumdatas[k].commentsSum+')</div>').appendTo($('.keyword-box'))
    }

    for(var j=0;j< c.customersdatas.length;j++){
        var imgItem;
        var dataAutor = c.customersdatas[j].customerAvotorr;
        var autor;
        if(dataAutor==""){
            autor = '../img/comment_h.jpg';
        }else{
            autor = dataAutor;
        }

        $('<div class="comment">'+
            '<div class="comment-user">'+
            '<div class="user-img"><img src="'+autor+'" alt="头像"></div>'+
            '<div class="user-info">'+
            '<span class="user-name">'+ c.customersdatas[j].customerPhone+'</span>'+
            '<span class="user-time">'+ c.customersdatas[j].createTime+'</span></div>'+
            //'<div class="user-star star_arr" id="user-star" data-score="'+c.customersdatas[j].gradedValue+'">'+
            //'<span id="add_star2" class="add-star2"></span>'+
            //'<span id="del_star2" class="del-star2"></span>' +
            //'</div>'+
            '</div><div class="comment-detail">'+ c.customersdatas[j].content+'</div>'+
            '</div>').insertBefore($('.view-all-comment'));
        //showStar2(c.customersdatas[j].gradedValue);
    }
    //单个评价分
    //showStar2('.star_arr',ac)
    function showStar2(obj,n){
        var ac = obj.attr('data-score');
        var readStar = obj.offsetWidth;
        var huiStar = $('.del_star2');
        var del_move2=(n*readStar)/5;

        $('.del_star2').css({'background-position':'-'+del_move2+'px 0px','left':''+del_move2+'px'})
        //huiStar.style.backgroundPosition=-del_move2+"px 0px";
        //huiStar.style.left=del_move2+"px";

    }
}




//店铺评分
function showStar(n){
     var con_wid=document.getElementById("star_con").offsetWidth;
     var del_star=document.getElementById("del_star");

    //透明星星移动的像素
    var del_move=(n*con_wid)/5;

    del_star.style.backgroundPosition=-del_move+"px 0px";
    del_star.style.left=del_move+"px";
}



//用户总评分
function showStar3(n){
    var con_wid3=document.getElementById("comment-star").offsetWidth;
    var del_star3=document.getElementById("del_star3");

    //透明星星移动的像素
    var del_move3=(n*con_wid3)/5;

    del_star3.style.backgroundPosition=-del_move3+"px 0px";
    del_star3.style.left=del_move3+"px";
}

//评价页
$('.view-all-comment,.comment-big-box').click(function () {
    window.location.href="comment_v2.html?shopId="+shopId;
})


//店铺导航
$('.address').click(function(){
    var url = encodeURI("map.html?shopName="+shopName+"&shopAddress="+shopAddress+"&shopPhone="+shopPhone+"&lnt="+lnt);
    window.open(url,"_self");
})

//分享
var ticket;
var timer;
var wxSha1;
$(function () {
    $.ajax({
        url:'/shareC/getAccessToken.json',
        dataType:'json',
        type:'post',
        success:function (data) {
            ticket = data.datas;
            timer = Date.parse(new Date());
            timer = timer / 1000;
            var WXsignature = 'jsapi_ticket=' + ticket + '&noncestr=Wm3WZYTPz0wzccnW&timestamp=' + timer + '&url=' + location.href.split('#')[0]
            wxSha1 = hex_sha1(WXsignature);

            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: 'wxfe59dbeae5082ce6', // 必填，公众号的唯一标识
                timestamp: timer, // 必填，生成签名的时间戳
                nonceStr: 'Wm3WZYTPz0wzccnW', // 必填，生成签名的随机串
                signature: wxSha1,// 必填，签名，见附录1
                jsApiList: ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });

            wx.ready(function(){
                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，
                wx.checkJsApi({
                    jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                    success: function(res) {
                        // 以键值对的形式返回，可用的api值true，不可用为false
                        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                    },
                    fail:function () {
                        mui.alert('您的微信版本过低，暂不支持分享，请升级微信')
                    }
                });

                //分享给朋友
                wx.onMenuShareAppMessage({
                    title: '分享一个产品，代购整座城市', // 分享标题
                    desc: '同城优选，助利商城', // 分享描述
                    link: 'http://www.ddmzl.com/m/html/shop_v2.html?shopId='+shopId+'&userId='+userId, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://www.ddmzl.com/m/img/share_logo.jpg', // 分享图标
                    type: '', // 分享类型,music、video或link，不填默认为link
                    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                    success: function () {
                        mui.toast('分享成功');
                        window.location.href='http://www.ddmzl.com/m/html/shop_v2.html?shopId='+shopId+'&userId='+userId;
                    },
                    cancel: function () {
                        mui.toast('您取消了分享')
                        // 用户取消分享后执行的回调函数
                    }
                });

                //分享到朋友圈
                wx.onMenuShareTimeline({
                    title: '分享一个产品，代购整座城市', // 分享标题
                    desc: '同城优选，助利商城', // 分享描述
                    link: 'http://www.ddmzl.com/m/html/shop_v2.html?shopId='+shopId+'&userId='+userId, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://www.ddmzl.com/m/img/share_logo.jpg', // 分享图标
                    success: function () {
                        mui.toast('分享成功');
                        $.ajax({
                            url:'/user/UpdateUserIntegral.json',
                            dataType:'json',
                            data:{
                                token:getItem('token'),
                            },
                            success:function(data){
                                mui.toast('分享成功');
                                window.location.href='http://www.ddmzl.com/m/html/shop_v2.html?shopId='+shopId+'&userId='+userId;
                            }
                        })
                    },
                    cancel: function () {
                        mui.toast('您取消了分享')
                        // 用户取消分享后执行的回调函数
                    }
                });
            });
        }
    })
})

$('.more').click(function () {
    //分享到朋友圈
    if (is_weixn()) {
        mui.alert('请点击右上角分享')
    }else{
        mui.alert('请在微信中打开')
    }
})

//function setPopOverMenu() {
    var uip = document.getElementById("topPopover");
    uip.style.position = "absolute";
    $(".mui-backdrop").click(function() {
        $("#topPopover").hide();
        $(".mui-backdrop").hide();
    });
    $(".mui-table-view-cell").click(function() {
        $("#topPopover").hide();
        $(".mui-backdrop").hide();
    });
//}

